package com.chuangjiangx.member.basic.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.chuangjiangx.commons.AppletVerifyUtils;
import com.chuangjiangx.commons.HttpMinimalUtils;
import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.basic.ddd.application.LoginApplication;
import com.chuangjiangx.member.basic.ddd.application.MemberApplication;
import com.chuangjiangx.member.basic.ddd.application.command.*;
import com.chuangjiangx.member.basic.ddd.domain.model.*;
import com.chuangjiangx.member.basic.ddd.domain.service.MemberRedisDomainService;
import com.chuangjiangx.member.common.utils.AIFace.*;
import com.chuangjiangx.member.common.AppletConstants;
import com.chuangjiangx.member.common.Constants;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.basic.web.request.LoginRequest;
import com.chuangjiangx.member.basic.web.request.WxGetOpenIdRequest;
import com.chuangjiangx.member.coupon.web.response.response.UploadedFileResponse;
import com.chuangjiangx.member.coupon.web.response.response.WxGetOpenIdResponse;
import com.chuangjiangx.member.basic.web.response.applet.AppletEntryResponse;
import com.chuangjiangx.member.basic.web.response.applet.WxJscode2session;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.chuangjiangx.member.basic.ddd.query.MerchantUserInfoQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDTO;
import com.chuangjiangx.member.common.utils.AIFaceUtils;
import com.chuangjiangx.member.common.utils.AIMethodUtils;
import com.chuangjiangx.member.common.utils.WxEncodeUtil;
import com.chuangjiangx.member.common.utils.WxSessionKeyUtil;
import com.chuangjiangx.publicmodule.domain.upload.service.UploadFileService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.chuangjiangx.member.basic.ddd.application.command.AIMethod.BIOASSAY_FACE;

/**
 * 小程序相关接口代码
 * @author cj-ch
 * @date 2018/10/21 下午12:12
 */
@Slf4j
@RestController
@RequestMapping(value = "/h5")
@Api(value = "会员小程序", tags = "会员小程序")
public class AppletController extends BaseController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberApplication memberApplication;

    @Autowired
    private MerchantUserInfoQuery merchantUserInfoQuery;

    @Autowired
    private MemberQuery memberQuery;
    @Autowired
    private LoginApplication loginApplication;
    @Autowired
    private WxAppletTokenRepository wxAppletTokenRepository;

    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    private MemberRepository memberRepository;
    @Autowired
    private MbrUserMappingRepository mbrUserMappingRepository;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MemberRedisDomainService memberRedisDomainService;




    /**
     * 会员小程序入口,第一个访问的接口
     * 判断用户身份是否是会员,是否录入了人脸信息
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "登录获取openId和sessionKey", httpMethod = "POST")
    @RequestMapping(value = "/getOpenId", method = RequestMethod.POST)
    public Response getOpenId(@RequestBody LoginRequest request) throws Exception {
        AppletEntryResponse res = new AppletEntryResponse();
        Long merchantId = request.getMerchantId();
        MbrUserContext userContext = loginService.currentUserContext();
        //此处代码包含过多逻辑处理，应在业务层编写
        if(isValidLogin(userContext,merchantId)){
            //已经登录了
            //有效的登录状态
            res.setOpenid(userContext.getSubOpenId());
            res.setIsmember(true);
            //是否已经录入人脸Id
            res.setHaveFace(StringUtils.isNotBlank(userContext.getFaceId()));
            //是否需要或取微信用户信息
            res.setIsneedWxUserInfo(StringUtils.isBlank(userContext.getHeadimgurl()));
            return ResponseUtils.success(res);
        } else {
            // 未登录
            WxAppletToken tokenVo = wxAppletTokenRepository.fromMerchantIdAndProductId(new MerchantId(merchantId), AppletConstants.MBR_APPLET_PID);
            if (tokenVo == null) {
                return ResponseUtils.error("9999", "该商户未申请小程序");
            }

            String appId = tokenVo.getAuthorizerAppid();
            String appSecret = tokenVo.getAuthorizerSecret();
            String aOpenid=null;
            String sessionKey=null;
            //区分开发和私有化部署的小程序，open_Id的获取方式不同
            if("wx9f8714b86025305a".equals(appId) || "wx679d28004fada30b".equals(appId)){
                String json = WxSessionKeyUtil.getOpenIdUrl("appid=" + appId + "&secret=" + appSecret + "&js_code=" + request.getJscode() + "&grant_type=authorization_code");
                if(StringUtils.isBlank(json)){
                    log.error("请求微信code2Session接口失败");
                    throw new BaseException("",Constants.GENERATE_ERROR);
                }
                WxJscode2session wxJscode2session = JacksonUtils.toObject(objectMapper, json, WxJscode2session.class);
                if(!wxJscode2session.ok()){
                    log.error("微信code2Session接口返回失败信息:{}" , wxJscode2session.getErrMsg());
                    throw new BaseException("",Constants.GENERATE_ERROR);
                }
                aOpenid = wxJscode2session.getOpenid();
                res.setOpenid(aOpenid);
                res.setSession_key(wxJscode2session.getSession_key());
            }else{
                WxGetOpenIdRequest vo = new WxGetOpenIdRequest();
                vo.setAppId(appId);
                vo.setJsCode(request.getJscode());
                String jsonText = JacksonUtils.toJson(this.objectMapper, vo);
                String entryStr = AppletVerifyUtils.sign(jsonText);
                RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(15000).build();
                HttpEntity entity = new StringEntity(entryStr, ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8));
                HttpMinimalUtils.RequestResult result = HttpMinimalUtils.post("http://applet.chuangjiangx.com/applet/getOpenId", entity, requestConfig);
                if (result.result) {
                        WxGetOpenIdResponse wxGetOpenIdResponse = JacksonUtils.toObject(objectMapper, result.content, WxGetOpenIdResponse.class);
                        if(StringUtils.isEmpty(wxGetOpenIdResponse.getData().getOpenid())){
                            throw new BaseException("",Constants.GENERATE_ERROR);
                        }
                        aOpenid = wxGetOpenIdResponse.getData().getOpenid();
                        sessionKey = wxGetOpenIdResponse.getData().getSession_key();
                }
                res.setOpenid(aOpenid);
                res.setSession_key(sessionKey);
            }

            // 查询用户信息
            MbrUserMapping mapping = mbrUserMappingRepository.getInMbrUserMappingByAopenId(merchantId,MbrUserMappingType.WX,aOpenid);
            // 当用户信息不为null 增加redis中的session
            if (mapping != null) {
                // 已经是会员自动登录
                MemberDTO member = memberQuery.queryByMemberId(mapping.getMemberId().getId());
                userContext = MbrUserContext.builder().build();
                userContext.setMemberId(member.getId());
                userContext.setMerchantId(merchantId);
                userContext.setSubAppId(appId);
                userContext.setSubOpenId(aOpenid);
                userContext.setMobile(member.getMobile());
                userContext.setSex(member.getSex());
                userContext.setName(member.getName());
                userContext.setHeadimgurl(member.getHeadimgurl());
                userContext.setFaceId(member.getFaceId());

                userContext.setMerchantUserId(
                        Optional.ofNullable(member.getRegisterMerchantUserId())
                            .orElse(merchantUserInfoQuery.getDefaultMerchantUserId(merchantId))
                );
                userContext.setAiFaceImg(mapping.getAiFaceImg());
                res.setIsmember(true);
                res.setHaveFace(StringUtils.isNotBlank(member.getFaceId()));
                //是否需要或取微信用户信息
                res.setIsneedWxUserInfo(StringUtils.isBlank(member.getHeadimgurl()));
            } else {
                //当用户信息不存在时
                userContext = MbrUserContext.builder().build();
                userContext.setSubOpenId(aOpenid);
                userContext.setSubAppId(appId);
                userContext.setMerchantId(merchantId);
                res.setIsmember(false);
                res.setHaveFace(false);
                res.setIsneedWxUserInfo(false);
            }
            redisTemplate.opsForValue()
                    .set(aOpenid,JacksonUtils.toJson(objectMapper,userContext),
                            1, TimeUnit.HOURS);
            return ResponseUtils.success(res);
        }
    }


    /**
     * 微信小程序获取用户手机号码
     * 授权通过后
     * @return
     */
    @ApiOperation(value = "对微信数据解密", httpMethod = "POST")
    @RequestMapping(value = "/decryptInfo", method = RequestMethod.POST)
    public Response decryptInfo(@RequestBody LoginRequest request, HttpServletRequest servletRequest)  {
        // 获取当前用户上下文
        MbrUserContext userContext = loginService.currentUserContext();
        String appId = userContext.getSubAppId();
        String decrypt = WxEncodeUtil.decrypt(appId, request.getEncryptedData(), request.getSessionKey(), request.getIv());
        if(StringUtils.isBlank(decrypt)){
            throw new BaseException("","解密手机号码失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        if (jsonObject == null) {
            ResponseUtils.error("9999", "解密微信数据失败");
        }
        // 手机号码
        String phoneNumber = (String) jsonObject.get("phoneNumber");
        if(StringUtils.isBlank(phoneNumber)){
            throw new BaseException("","解密数据中手机号码不存在");
        }
        // 查询会员 ,
        // 判断是否会员;是,自动登录;否,自动注册;绑定小程序openid
        MemberDTO member = memberQuery.queryByMerchantAndMobile(request.getMerchantId(), phoneNumber);
        if(member == null){
            //自动注册
            userContext.setMobile(phoneNumber);
            userContext.setMerchantUserId(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId()));
            Member m = loginApplication.wxAppletRegister(userContext);
            userContext.setMemberId(m.getId().getId());
        } else {
            // 是会员
            userContext.setMemberId(member.getId());
            userContext.setMobile(member.getMobile());
            userContext.setSex(member.getSex());
            userContext.setName(member.getName());
            userContext.setHeadimgurl(member.getHeadimgurl());
            userContext.setFaceId(member.getFaceId());
            userContext.setMerchantUserId(
                    Optional.ofNullable(member.getRegisterMerchantUserId())
                            .orElse(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId()))
            );
        }
        // 绑定小程序openid
        MbrUserMapping userMapping = new MbrUserMapping(
                new MemberId(userContext.getMemberId()),
                new MerchantId(userContext.getMerchantId()),
                null,
                null,
                MbrUserMappingType.WX,
                userContext.getSubOpenId(),
                null
        );
        loginApplication.bindWXUserMapping(userContext.getMemberId(),userMapping);
        loginService.updateUserContext(userContext);
        return ResponseUtils.success(jsonObject);
    }


    /**
     * 获取用户手机号码,授权拒绝后
     *
     * @return
     */
    @ApiOperation(value = "会员小程序登录接口-验证码", httpMethod = "POST")
    @RequestMapping(value = "/appletLogin", method = RequestMethod.POST)
    public Response appletLogin(HttpServletRequest request, @RequestBody LoginRequest loginRequest) throws Exception {
        // 验证码
        checkVerifyCode(loginRequest);
        MbrUserContext userContext = loginService.currentUserContext();
        String mobile = loginRequest.getMobile();
        // 判断是否会员;是,自动登录;否,自动注册;绑定小程序openid
        Member member = memberRepository.fromMerchantIdAndMobile(
                new MerchantId(loginRequest.getMerchantId()), mobile);
        if (member != null) {
            // 已经是会员
            userContext.setMemberId(member.getId().getId());
            userContext.setMobile(member.getMobile());
            userContext.setSex(member.getSex().value);
            userContext.setName(member.getName());
            userContext.setHeadimgurl(member.getHeadimgurl());
            userContext.setFaceId(member.getFaceId());
            userContext.setMerchantUserId(
                    Optional.ofNullable(member.getOperationInfo().getMerchantUserId())
                            .orElse(
                                    new MerchantUserId(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId())))
                            .getId()
            );
        } else {
            //自动注册
            userContext.setMobile(mobile);
            userContext.setMerchantUserId(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId()));
            member = loginApplication.wxAppletRegister(userContext);
            userContext.setMemberId(member.getId().getId());
        }
        userContext.setMerchantId(loginRequest.getMerchantId());
        userContext.setMobile(mobile);

        // 绑定小程序openid
        MbrUserMapping userMapping = new MbrUserMapping(
                new MemberId(userContext.getMemberId()),
                new MerchantId(userContext.getMerchantId()),
                null,
                null,
                MbrUserMappingType.WX,
                userContext.getSubOpenId(),
                null
        );
        loginApplication.bindWXUserMapping(userContext.getMemberId(),userMapping);

        loginService.updateUserContext(userContext);
        return ResponseUtils.success();
    }

    /**
     * 新增人脸
     * @return
     * @throws Exception
     */
    private Response addFace(MbrUserContext userContext) throws Exception {

        AIRequestCommand command = new AIRequestCommand();
        command.setImage(userContext.getAiFaceImg());
        command.setAiFaceImageType(AIFaceImageType.IMAGE_URL);
        command.setAiMethod(AIMethod.ADD_FACE);
        command.setUnion_id(System.getProperty("CUSTOMER_PRODUCT_ID") + "-" + userContext.getMerchantId());
        // 调用AI录入人脸接口获取faceId
        AiAddFaceResponse aiAddFaceResponse = (AiAddFaceResponse) AIFaceUtils.aiMethod(command);
        aiAddFaceResponse.setErrorMsg(AiExceptionCode.get(aiAddFaceResponse.getErrorCode()).msg);
        if (aiAddFaceResponse != null) {
            if (!AIConstant.CODE_SUCCESS.equals(aiAddFaceResponse.getErrorCode())) {
                throw new AiException(aiAddFaceResponse.getErrorMsg());
            }
            AIFaceDalCommand dalCommand = new AIFaceDalCommand();
            dalCommand.setAiMethod(AIMethod.ADD_FACE);
            dalCommand.setAiResponse(aiAddFaceResponse);
            dalCommand.setMbrUserContext(userContext);
            memberApplication.updateAIFaceMember(dalCommand);
            return ResponseUtils.success();
        } else {
            throw new AiException("AI人脸库发生未知异常");
        }
    }


    /**
     * 更新人脸
     * @return
     * @throws Exception
     */
    private Response updateFace(MemberDTO member,MbrUserContext userContext) throws Exception {

        AIRequestCommand command = new AIRequestCommand();
        command.setUnion_id(System.getProperty("CUSTOMER_PRODUCT_ID") + "-" + userContext.getMerchantId());
        command.setAiMethod(AIMethod.UPDATE_FACE);
        command.setFace_id(member.getFaceId());
        command.setImage(userContext.getAiFaceImg());
        command.setAiFaceImageType(AIFaceImageType.IMAGE_URL);
        AIUpdateFaceResponse aiUpdateFaceResponse = (AIUpdateFaceResponse) AIFaceUtils.aiMethod(command);
        aiUpdateFaceResponse.setErrorMsg(AiExceptionCode.get(aiUpdateFaceResponse.getErrorCode()).msg);
        if (aiUpdateFaceResponse != null) {
            if (!AIConstant.CODE_SUCCESS.equals(aiUpdateFaceResponse.getErrorCode())) {
                throw new AiException(aiUpdateFaceResponse.getErrorMsg());
            }
            AIFaceDalCommand dalCommand = new AIFaceDalCommand();
            dalCommand.setAiMethod(AIMethod.UPDATE_FACE);
            dalCommand.setAiResponse(aiUpdateFaceResponse);
            dalCommand.setMbrUserContext(userContext);
            memberApplication.updateAIFaceMember(dalCommand);
            return ResponseUtils.success();
        } else {
            throw new AiException("AI人脸库发生未知异常");
        }

    }

    /**
     * AI 1.0
     * 活体检测
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "AI人脸", httpMethod = "POST")
    @RequestMapping(value = "/bioassayFace", method = RequestMethod.POST)
    @Login
    public Response bioassayFace(MultipartFile file, HttpServletRequest request) throws Exception {
        MbrUserContext userContext = loginService.currentUserContext();

        // 查询会员信息
        MemberDTO member = memberQuery.queryByMemberId(userContext.getMemberId());
        // 上传人脸文件
        String fileKey = uploadFileService.uploadFile(file.getInputStream(), file.getOriginalFilename());
        UploadedFileResponse response = new UploadedFileResponse(fileKey,uploadFileService.getDownloadUrl(fileKey));

        AIRequestCommand command = new AIRequestCommand();
        command.setAiMethod(BIOASSAY_FACE);
        command.setAiFaceVideoType(AIFaceVideoType.getType(request.getParameter("videoType")));
        command.setVideo_url(response.getUrl());
        // 调用AI人脸活体检测接口
        AiBioassayFaceResponse bioassayFaceResponse = (AiBioassayFaceResponse) AIFaceUtils.aiMethod(command);
        bioassayFaceResponse.setErrorMsg(AiExceptionCode.get(bioassayFaceResponse.getErrorCode()).msg);
        if (bioassayFaceResponse != null) {
            // 人脸活体检测成功
            userContext.setAiFaceImg((String) bioassayFaceResponse.getImageUrl());
            if (AIConstant.CODE_SUCCESS.equals(bioassayFaceResponse.getErrorCode())) {

                if(StringUtils.isBlank(member.getFaceId())){
                    //新增
                    addFace(userContext);
                } else {
                    //更新
                    updateFace(member,userContext);
                }

                // 绑定人脸图片地址
                MbrUserMapping userMapping = new MbrUserMapping(
                        new MemberId(member.getId()),
                        new MerchantId(member.getMerchantId()),
                        null,
                        null,
                        MbrUserMappingType.WX,
                        null,
                        userContext.getAiFaceImg()
                );
                loginApplication.bindWXUserMapping(userContext.getMemberId(),userMapping);
                loginService.updateUserContext(userContext);
            } else {
                throw new AiException(bioassayFaceResponse.getErrorMsg());
            }
        } else {
            throw new AiException("AI人脸库发生未知异常");
        }
        return ResponseUtils.success();
    }

    /**
     * 获取用户头像信息通过授权后
     * 小程序获取到了用户的昵称\性别等信息后调用此接口
     * @param loginRequest
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "微信用户信息获取", httpMethod = "POST")
    @RequestMapping(value = "/memberInfo", method = RequestMethod.POST)
    @Login
    public Response memberInfo(@RequestBody LoginRequest loginRequest, HttpServletRequest request) throws Exception {
        MbrUserContext userContext = loginService.currentUserContext();
        WechatMemberInfo info = JSONObject.parseObject(loginRequest.getMemberInfo(), WechatMemberInfo.class);
        ModifyMemberCommand command = new ModifyMemberCommand();
        command.setMemberId(userContext.getMemberId());
        command.setHeadimgurl(info.getAvatarUrl());
        command.setMerchantUserId(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId()));
        command.setSex(info.getGender().equals("1") ? (byte)0 : (byte)1);
        command.setName(info.getNickName());
        command.setMerchantId(userContext.getMerchantId());
        memberApplication.modifyMember(command);
        return ResponseUtils.success();
    }


    /**
     * AI 2.0
     * @param request
     * @return
     * @throws AiException
     */
    @ApiOperation(value = "AI会员采集预处理", httpMethod = "POST",tags = "AI2.0")
    @RequestMapping(value = "/preInputFace", method = RequestMethod.POST)
    @Login
    public Response preInputFace(HttpServletRequest request) throws AiException {
        MbrUserContext userContext = loginService.currentUserContext();
        AIAddFacePerProcessRequest perProcessRequest = new AIAddFacePerProcessRequest();
        perProcessRequest.setUnion_id(System.getProperty("CUSTOMER_PRODUCT_ID") + "-" + userContext.getMerchantId());
        perProcessRequest.setMember_id(userContext.getMemberId() + "");
        AIBaseResponse<AIAddFacePerProcessResponse> baseResponse = AIMethodUtils.perInputFace(perProcessRequest);
        if (AIConstant.CODE_SUCCESS.equals(baseResponse.getErrorCode())) {
            return ResponseUtils.success(baseResponse.getData());
        }
        return ResponseUtils.error(baseResponse.getErrorCode(), AiExceptionCode.get(baseResponse.getErrorCode()).msg);

    }

    /**
     * AI 2.0
     * @param request
     * @return
     * @throws AiException
     */
    @ApiOperation(value = "AI会员人脸采集", httpMethod = "POST",tags = "AI2.0")
    @RequestMapping(value = "/inputFace", method = RequestMethod.POST)
    @Login
    public Response inputFace(MultipartFile file, HttpServletRequest request) throws Exception {
        //上传oss
        String fileKey = uploadFileService.uploadFile(file.getInputStream(), file.getOriginalFilename());
        UploadedFileResponse response = new UploadedFileResponse(fileKey,uploadFileService.getDownloadUrl(fileKey));
        MbrUserContext userContext = loginService.currentUserContext();
        AIFaceInputRequest inputRequest = new AIFaceInputRequest();
        //拼装ai接口参数
        inputRequest.setUnion_id(System.getProperty("CUSTOMER_PRODUCT_ID") + "-" + userContext.getMerchantId());
        inputRequest.setMember_id(userContext.getMemberId() + "");
        inputRequest.setFeature_image(response.getUrl());
        String featureFace = request.getParameter("aiFeatureFace");
        if (StringUtils.isBlank(featureFace) || "null".equals(featureFace)) {
            throw new AiException("无法正确识别特征码");
        }
        inputRequest.setFeature_face(featureFace);
        //请求ai接口
        AIBaseResponse<AIFaceInputResponse> inputResponse = AIMethodUtils.inputFace(inputRequest);
        inputResponse.setErrorMsg(AiExceptionCode.get(inputResponse.getErrorCode()).msg);
        if (inputResponse == null) {
            throw new AiException("人脸采集接口回调数据缺失");
        }
        if (AIConstant.CODE_SUCCESS.equals(inputResponse.getErrorCode())) {
            AIFaceInputResponse aiFaceInputResponse = inputResponse.getData();
            //当collection_over字段为True 说明采集完毕，更新数据库操作
            if ( Boolean.TRUE.equals(aiFaceInputResponse.getCollectionOver())) {
                String imageUrl = (String) aiFaceInputResponse.getFaceImage();
                String faceId = (String) aiFaceInputResponse.getFaceId();
                loginApplication.entryFaceSuccess(
                        userContext.getMemberId(),
                        userContext.getMerchantId(),
                        imageUrl,
                        faceId
                );
                userContext.setAiFaceImg(imageUrl);
                userContext.setFaceId(faceId);
                loginService.updateUserContext(userContext);
            }
            return ResponseUtils.success(inputResponse.getData());
        }
        return ResponseUtils.error(inputResponse.getErrorCode(), AiExceptionCode.get(inputResponse.getErrorCode()).msg);

    }

    /**
     * AI 2.0
     * @param request
     * @return
     * @throws AiException
     */
    @ApiOperation(value = "AI人脸更新采集", httpMethod = "POST",tags = "AI2.0")
    @RequestMapping(value = "/updateInputFace", method = RequestMethod.POST)
    @Login
    public Response updateInputFace(MultipartFile file, HttpServletRequest request) throws Exception {
        //上传oss
        String fileKey = uploadFileService.uploadFile(file.getInputStream(), file.getOriginalFilename());
        UploadedFileResponse response = new UploadedFileResponse(fileKey,uploadFileService.getDownloadUrl(fileKey));
        MbrUserContext userContext = loginService.currentUserContext();
        UpdateFaceInputRequest aiUpdateRequest = new UpdateFaceInputRequest();
        //拼装ai接口参数
        aiUpdateRequest.setUnion_id(System.getProperty("CUSTOMER_PRODUCT_ID") + "-" + userContext.getMerchantId());
        aiUpdateRequest.setFeature_image(response.getUrl());
        String featureFace = request.getParameter("aiFeatureFace");
        if (StringUtils.isBlank(featureFace) || "null".equals(featureFace)) {
            throw new AiException("无法正确识别特征码");
        }
        aiUpdateRequest.setFeature_face(featureFace);
        aiUpdateRequest.setMember_id(userContext.getMemberId() + "");
        aiUpdateRequest.setFace_id(userContext.getFaceId());
        //请求ai接口
        AIBaseResponse<UpdateFaceInputResponse> baseResponse = AIMethodUtils.updateFace(aiUpdateRequest);
        if (baseResponse == null) {
            throw new AiException("更新人脸返回参数为空");
        }
        if (AIConstant.CODE_SUCCESS.equals(baseResponse.getErrorCode())) {
            UpdateFaceInputResponse updateFaceInputResponse = baseResponse.getData();
            //当更新了正脸时候，会返回face_image，此时更新数据库
            if (StringUtils.isNotBlank((String)updateFaceInputResponse.getFaceImage())) {
                String faceImg = (String) updateFaceInputResponse.getFaceImage();
                loginApplication.inputFaceImgUrlUserMapping(
                        userContext.getMemberId(),
                        userContext.getMerchantId(),
                        faceImg
                );
                userContext.setAiFaceImg(faceImg);
                loginService.updateUserContext(userContext);
            }
            return ResponseUtils.success(baseResponse.getData());
        }
        return ResponseUtils.error(baseResponse.getErrorCode(), AiExceptionCode.get(baseResponse.getErrorCode()).msg);

    }
}
